package com.xhu.service.impl;

import com.xhu.mapper.PermissionMapper;
import com.xhu.pojo.Permission;
import com.xhu.pojo.Role;
import com.xhu.pojo.User;
import com.xhu.service.PermissionService;
import com.xhu.utils.ResponseMessage;
import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public ResponseMessage permissionList(String username) {
        //1.redis为空会报错
        if (StringUtil.isNullOrEmpty(username))
            return new ResponseMessage(500, "username is empty");
        //2.取出数据内容
        User user =(User)redisTemplate.opsForValue().get(username);
        //3.通过user对象拿到角色名字
        String roleName = user.getRole().getRoleName();
        Role role=user.getRole();
        //4.通过角色名查询菜单栏
        List<Permission> permissionList = permissionMapper.permissionList(roleName);
        //5.封装数据
        //存放菜单信息
        List<Permission> dataPermission=new ArrayList<>();
        //5.1 遍历permissionList
        for (Permission parentPermission : permissionList) {//一级菜单
            List<Permission> childrenList=new ArrayList<>();
            if(parentPermission.getParentId()==0){
                for(Permission childPermission:permissionList){//二级菜单
                    if(childPermission.getParentId().equals(parentPermission.getNodeId())){
                        //把二级菜单封装成一组
                        childrenList.add(childPermission);
                    }
                }
                //把二级菜单放入一级菜单中
                parentPermission.setChildrenList(childrenList);
                //封装所有菜单
                dataPermission.add(parentPermission);
                //System.out.println(dataPermission);
            }
        }
        return new ResponseMessage(200,roleName+" permission list",dataPermission);
    }


}
